package com.ruoyi.common.utils.mp;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;

@Slf4j
@Component
public class AliOSSUtils {

    //    "LTAI4GA7YVgfG9cEEGUNvUL4"
    @Value("${oss.ali.access-key-id}")
    private String accessKeyId;
    //    ="Bc0LSATLi4UMCaD7NOibWmhESwBxtp"
    @Value("${oss.ali.access-key-secret}")
    private String accessKeySecret;
    //    ="oss-cn-chengdu.aliyuncs.com"
    @Value("${oss.ali.endpoint}")
    private String endpoint;
    //    ="mgmf"
    @Value("${oss.ali.bucket-name}")
    private String bucketName;
//    enable: true
//    access-key-id:
//    access-key-secret:
//    endpoint:
//    bucket-name:

    /**
     * 上传文件, OSS的java SDK 目前仅支持put上传
     *
     * @param fileName    文件名
     * @param inputStream 文件流
     * @return
     */
    public String uploadFileToOSS(String fileName, InputStream inputStream) {
        log.info("oss-文件正在上传");
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            oss.putObject(bucketName, fileName, inputStream);
        } catch (OSSException oe) {
            log.error("aliyun OSS 上传文件失败{},Error Message:{}, Error Code:{}, Request ID: {}, Host ID: {} ",
                    fileName, oe.getErrorCode(), oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
        } finally {
            oss.shutdown();
        }
        log.info("oss-文件完成上传");
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
    @SneakyThrows
    public String uploadZipFile(File file) {
        final InputStream inputStream = FileUtil.getInputStream(file);
        final String originalFilename = FileUtil.getName(file);
        return uploadFileToOSS(originalFilename,inputStream);
    }

    @SneakyThrows
    public String uploadImgFile(MultipartFile file) {
        final InputStream inputStream = file.getInputStream();
        final String originalFilename = file.getOriginalFilename();
        return uploadFileToOSS(originalFilename,inputStream);
    }
}
